<!DOCTYPE html>
<html lang="zh-cn">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>LuatOS 在线模拟</title>
    <meta name="description" content="在线模拟LuatOS">
    <meta name="author" content="chenxuuu">
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <script src="js/fengari-web.js" type="text/javascript"></script>
    <link rel="stylesheet" href="codemirror-5.49.2/lib/codemirror.css" />
    <script src="codemirror-5.49.2/lib/codemirror.js"></script>
    <script src="codemirror-5.49.2/mode/lua/lua.js"></script>
    <link rel="stylesheet" href="codemirror-5.49.2/theme/mdn-like.css" />
    <style>
        .CodeMirror-line {
            font-family:  'Sarasa Mono SC',Consolas, 'Microsoft Yahei' !important;
            font-size: 14px !important;
        }
    </style>
</head>

<body>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                <h3>
                    实验项目：打印日志
                </h3>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <button id="runButton" class="btn btn-sm btn-success" type="button" onclick="runCode()">
                    运行
                </button>
                <button id="stopButton" class="btn btn-sm btn-danger" type="button" onclick="stopCode()" disabled>
                    停止
                </button>
                <textarea class="form-control" id="luaCode" name="code">
log = require("log")
sys = require("sys")

--启动一个定时器
sys.timerLoopStart(function()
    log.info("timestemp",os.time())
end,1000)

--新建任务，每休眠2000ms继续一次
sys.taskInit(function()
    local count = 0
    while true do
        sys.wait(2000)--等待2000ms
        count = count + 1
        log.info("task","运行了",count,"次")
    end
end)

--运行lua task，只能调用一次，而且必须写在末尾
sys.run()</textarea>
            </div>
            <div class="col-md-6">
                <p>日志输出：</p>
                <textarea class="form-control" id="output" readonly="true"
                    style="position: relative;width: 100%;height: 500px;">虚拟机未加载</textarea>
            </div>
        </div>
    </div>
    <div style="text-align: center;"><a href="https://luatos.com" target="_blank">LuatOS 首页</a>
    <div id="qrcode"></div>
    </div>
    <script src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/luaTask.js"></script>
    <script>

Date.prototype.Format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

var editor = CodeMirror.fromTextArea(document.getElementById("luaCode"), {
    mode: "text/x-lua", //实现lua代码高亮
    lineNumbers: true,  //显示行号
    theme: "mdn-like",  //设置主题
    indentUnit: 4,
    indentWithTabs: true,
    matchBrackets: true,
});
editor.setSize("100%", 600);

function luaPrint(s) {
    $("#output").append("["+new Date().Format("HH:mm:ss.S")+"] ");
    if(typeof(s) != "string")
        s = "";
    var textarea = $("#output").append(s.replace("<","&lt;") + "\r\n");
    textarea.scrollTop(textarea[0].scrollHeight - textarea.height());
}

function runCode() {
    var code = editor.getValue();
    newLuaState();
    $("#runButton").prop("disabled", true);
    $("#stopButton").prop("disabled", false);
    try {
        var r = luaTask_doString(code);
        if(!r.success) {
            luaPrint("虚拟机报错：");
            luaPrint(r.error);
        }
    }
    catch (err) {
        luaPrint("js环境报错：");
        luaPrint(err);
    }
}

function stopCode() {
    $("#runButton").prop("disabled", false);
    $("#stopButton").prop("disabled", true);
    luaTask_clean();
    luaPrint("虚拟机已停止运行");
}

function newLuaState() {
    luaTask_clean();
    luaTask_create();
    luaTask_doString(`
js = require "js"
--重写print函数
function print(...)
    local out = {}
    for i=1,select('#', ...) do
        table.insert(out,tostring(select(i, ...)))
    end
    js.global:luaPrint(table.concat(out,"\t"))
end
package.path = "./lua/?.lua"
require("head")`);
    $("#output").text("");
    luaPrint("虚拟机初始化完毕");
    luaTask_print = luaPrint;
}
$("#stopButton").prop("disabled", true);
    </script>
    <script>
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "https://hm.baidu.com/hm.js?2e02fb796d5ae8812686e6270227de97";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>
</body>

</html>
